import NumberCalc from "../tools/calculator";

/** 设置配置项 */
export interface SetOptions {
    /** 超时毫秒数 */
    Timeout?: number;
}
/** 保存数据信息 */
interface SaveDataInfo {
    /** 写入时的时间戳 */
    WriteTimeStamp: number;
    /** 保存时写入的配置项信息 */
    SetOptions: SetOptions;
}

/** 本地缓存数据 */
export default class WebCache {
    /**
     * 设置缓存
     * @param key 键
     * @param data 值
     * @param [option] 设置配置项(选填)
     */
    public Set(key: string, data: string, option?: SetOptions): void {
        localStorage.setItem(key, data);
        // 同步保存配置信息
        let option_key = this.ToOptionKey(key);
        let option_json = JSON.stringify({
            SetOptions: option,
            WriteTimeStamp: this.GetNowTimeStamp()
        } as SaveDataInfo);
        localStorage.setItem(option_key, option_json);
    }
    private ToOptionKey(key: string) {
        return `${key}$option`;
    }
    private GetNowTimeStamp(): number {
        return new Date().getTime();
    }
    /**
     * 获取键的值
     * @param key 键
     * @returns 保存的值内容, 如果过期返回 null
     */
    public Get(key: string): string {
        let data = localStorage.getItem(key);
        if (data === null) {
            return null;
        }
        let option_key = this.ToOptionKey(key);
        let option = JSON.parse(localStorage.getItem(option_key)) as SaveDataInfo;
        if ((option.SetOptions?.Timeout || 0) > 0) {
            let nowTimeStamp = this.GetNowTimeStamp();
            if (nowTimeStamp >= NumberCalc.Sun(option.SetOptions.Timeout, option.WriteTimeStamp)) {
                localStorage.removeItem(key);
                localStorage.removeItem(option_key);
                return null;
            }
        }
        return data;
    }
}
